package com.cmh.fantasy.serialize;


import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.objenesis.ObjenesisStd;

public class ProtostuffUtils{

    private static ObjenesisStd objenesisBase =  new ObjenesisStd(true);

    public  static byte[]  serialize(Object obj){
        Class clz = obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema schema = RuntimeSchema.createFrom(clz);
            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            throw e;
        } finally {
            buffer.clear();
        }
    }

    public static <T>T deserialize(byte[] serializeBytes , Class<T> clazz){
        T message = objenesisBase.newInstance(clazz); // <1>
        Schema<T> schema = RuntimeSchema.createFrom(clazz);
        ProtostuffIOUtil.mergeFrom(serializeBytes, message, schema);
        return message;
    }

}
